<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/%E7%97%95%E8%BF%B9.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/%E7%97%95%E8%BF%B9.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">

<link rel="stylesheet" href="//fonts.lug.ustc.edu.cn/css?family=Lato:300,300italic,400,400italic,700,700italic|Gabriola:300,300italic,400,400italic,700,700italic|Arial:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-minimal.min.css">
  <script src="/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"tian_yu_ting.gitee.io","root":"/","scheme":"Gemini","version":"7.7.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"mac"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":true,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="Python2.x与3.x版本区别Python的3.0版本，常被称为Python 3000，或简称Py3k。相对于Python的早期版本，这是一个较大的升级。 为了不带入过多的累赘，Python 3.0在设计的时候没有考虑向下相容。">
<meta property="og:type" content="article">
<meta property="og:title" content="python基础知识(四)">
<meta property="og:url" content="https://tian_yu_ting.gitee.io/Python/Python_id_19.html">
<meta property="og:site_name" content="Yu ting&#39;s blog">
<meta property="og:description" content="Python2.x与3.x版本区别Python的3.0版本，常被称为Python 3000，或简称Py3k。相对于Python的早期版本，这是一个较大的升级。 为了不带入过多的累赘，Python 3.0在设计的时候没有考虑向下相容。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2019-05-29T16:00:00.000Z">
<meta property="article:modified_time" content="2020-06-02T01:33:42.369Z">
<meta property="article:author" content="Yu ting">
<meta property="article:tag" content="Python">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://tian_yu_ting.gitee.io/Python/Python_id_19.html">

<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true
  };
</script>

  
  
    <script src="/js/cursor/love.min.js"></script>
  

  <title>python基础知识(四) | Yu ting's blog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

  <script>
    var mobileBtn = function f() {
        var toggleMenu = document.getElementsByClassName("menu-toggle")[0];
        var mobileMenu = document.getElementById("mobile-menu");
        if(toggleMenu.classList.contains("active")){
           toggleMenu.classList.remove("active")
            mobileMenu.classList.remove("active")
        }else{
            toggleMenu.classList.add("active")
            mobileMenu.classList.add("active")
        }
    }
  </script>

   <!-- 不知道是什么玩意 -->
  <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />
<link rel="alternate" href="/atom.xml" title="Yu ting's blog" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage" style="background-image:url(/images/14.jpg);background-repeat:no-repeat;background-attachment: fixed;">


  <div class="container use-motion">
    <!-- 网页上方的黑色长线 -->
    <div class="headband"></div>
    
    <!-- 在首页添加github图标 -->
<!--     <a href="https://github.com/h4055874" target="_blank" rel="noopener" class="github-corner" aria-label="View source on GitHub">
      <svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path>
      </svg>
    </a>
      <style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style> -->
    <!--  -->

    <!-- -->

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Yu ting's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">I only for you!</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签<span class="badge">66</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类<span class="badge">16</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档<span class="badge">171</span></a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-fw fa-user"></i>关于</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
        <!--
        <input id="switch_default" type="checkbox" class="switch_default">
        <label for="switch_default" class="toggleBtn"></label>
        -->
      </li>
  </ul>

<style>
    /*input css begin*/
*{
    -webkit-tap-highlight-color: rgba(0,0,0,0);
}
/* input[type="checkbox"],input[type="radio"]{
    display: none;
    width: 0;
    height: 0;
    visibility: hidden;
} */
input[type="checkbox"]:checked + label:after{
    transition: all 0.3s ease-in;
}
input[type="checkbox"]:not(:checked) + label:after {
    transition: all 0.3s ease-out;
}
input[type="checkbox"]:checked + label,
input[type="checkbox"]:not(:checked) + label{
    transition: all 0.3s ease-in-out;
}
input[type="checkbox"]:checked + label:before,input[type="checkbox"]:checked + label i:before,input[type="checkbox"]:not(:checked) + label i:before,
input[type="checkbox"]:checked + label i:after,input[type="checkbox"]:not(:checked) + label i:after,input[type="checkbox"]:not(:checked) + label:before{
    transition: all 0.3s ease-in-out;
}
input[type="radio"]:checked + label:after,
input[type="radio"]:not(:checked) + label:after {
    transition: all 0.3s ease-in-out;
}
.switch_default[type="checkbox"]{
    display: none;
}
.switch_default + label{
     background-color: #e6e6e6;
     border-radius:7px;
     cursor: pointer;
     display: inline-block;
     height: 14px;
     position: relative;
     box-shadow: 0.2px 0.2px 1px 0.5px rgb(180,180,180);
     width: 30px;
 }
.switch_default + label:after{
    background-color: #fff;
    border-radius: 50%;
    content: "";
    height: 12px;
    left: 1px;
    position: absolute;
    top: .5px;
    width: 12px;
    box-shadow: 0.2px 0.2px 1px 0.5px rgb(180,180,180);
}
.switch_default:checked + label{
    background-color: #1ABC9C;
    box-shadow:none;
}
.switch_default:checked + label:after{
    left: 17px;
}
</style>
</nav>
  <div class="site-search">
    <div class="search-pop-overlay">
  <div class="popup search-popup">
      <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocorrect="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

  </div>
</div>

  </div>
</div>
    </header>

    <!-- -->
    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>


    <main class="main">
    <!--sm -->
      <div class="main-inner">
        <div class="content-wrap">
          


          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://tian_yu_ting.gitee.io/Python/Python_id_19.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.png">
      <meta itemprop="name" content="Yu ting">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Yu ting's blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          python基础知识(四)
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2019-05-30 00:00:00" itemprop="dateCreated datePublished" datetime="2019-05-30T00:00:00+08:00">2019-05-30</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-06-02 09:33:42" itemprop="dateModified" datetime="2020-06-02T09:33:42+08:00">2020-06-02</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Python/" itemprop="url" rel="index"><span itemprop="name">Python</span></a>
                </span>
            </span>

          
            <span id="/Python/Python_id_19.html" class="post-meta-item leancloud_visitors" data-flag-title="python基础知识(四)" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/Python/Python_id_19.html#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/Python/Python_id_19.html" itemprop="commentCount"></span>
    </a>
  </span>
  
  <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>5.7k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="fa fa-clock-o"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>5 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h3 id="Python2-x与3-x版本区别"><a href="#Python2-x与3-x版本区别" class="headerlink" title="Python2.x与3.x版本区别"></a>Python2.x与3.x版本区别</h3><p>Python的3.0版本，常被称为Python 3000，或简称Py3k。相对于Python的早期版本，这是一个较大的升级。</p>
<p>为了不带入过多的累赘，Python 3.0在设计的时候没有考虑向下相容。</p>
<a id="more"></a>

<p>许多针对早期Python版本设计的程式都无法在Python 3.0上正常执行。</p>
<p>为了照顾现有程式，Python 2.6作为一个过渡版本，基本使用了Python 2.x的语法和库，同时考虑了向Python 3.0的迁移，允许使用部分Python 3.0的语法与函数。</p>
<p>新的Python程式建议使用Python 3.0版本的语法。</p>
<p>除非执行环境无法安装Python 3.0或者程式本身使用了不支援Python 3.0的第三方库。目前不支援Python 3.0的第三方库有Twisted, py2exe, PIL等。</p>
<p>大多数第三方库都正在努力地相容Python 3.0版本。即使无法立即使用Python 3.0，也建议编写相容Python 3.0版本的程式，然后使用Python 2.6, Python 2.7来执行。</p>
<p>Python 3.0的变化主要在以下几个方面:</p>
<hr>
<h4 id="print-函数"><a href="#print-函数" class="headerlink" title="print 函数"></a>print 函数</h4><p>print语句没有了，取而代之的是print()函数。 Python 2.6与Python 2.7部分地支持这种形式的print语法。在Python 2.6与Python 2.7里面，以下三种形式是等价的：</p>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="builtin-name">print</span> <span class="string">"fish"</span></span><br><span class="line"><span class="builtin-name">print</span> (<span class="string">"fish"</span>) #注意print后面有个空格</span><br><span class="line"><span class="builtin-name">print</span>(<span class="string">"fish"</span>) #<span class="builtin-name">print</span>()不能带有任何其它参数</span><br></pre></td></tr></table></figure>

<p>然而，Python 2.6实际已经支持新的print()语法：</p>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> __future__ import print_function</span><br><span class="line"><span class="builtin-name">print</span>(<span class="string">"fish"</span>, <span class="string">"panda"</span>, <span class="attribute">sep</span>=<span class="string">', '</span>)</span><br></pre></td></tr></table></figure>

<hr>
<h4 id="Unicode"><a href="#Unicode" class="headerlink" title="Unicode"></a>Unicode</h4><p>Python 2 有 ASCII str() 类型，unicode() 是单独的，不是 byte 类型。</p>
<p>现在， 在 Python 3，我们最终有了 Unicode (utf-8) 字符串，以及一个字节类：byte 和 bytearrays。</p>
<p>由于 Python3.X 源码文件默认使用utf-8编码，这就使得以下代码是合法的：</p>
<figure class="highlight ruby"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;</span>&gt; 中国 = <span class="string">'china'</span> </span><br><span class="line"><span class="meta">&gt;&gt;</span>&gt;print(中国) </span><br><span class="line">china</span><br></pre></td></tr></table></figure>

<p>Python 2.x</p>
<figure class="highlight taggerscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; str = "我爱北京天安门"</span><br><span class="line">&gt;&gt;&gt; str</span><br><span class="line">'<span class="symbol">\x</span>e6<span class="symbol">\x</span>88<span class="symbol">\x</span>91<span class="symbol">\x</span>e7<span class="symbol">\x</span>88<span class="symbol">\x</span>b1<span class="symbol">\x</span>e5<span class="symbol">\x</span>8c<span class="symbol">\x</span>97<span class="symbol">\x</span>e4<span class="symbol">\x</span>ba<span class="symbol">\x</span>ac<span class="symbol">\x</span>e5<span class="symbol">\x</span>a4<span class="symbol">\x</span>a9<span class="symbol">\x</span>e5<span class="symbol">\x</span>ae<span class="symbol">\x</span>89<span class="symbol">\x</span>e9<span class="symbol">\x</span>97<span class="symbol">\x</span>a8'</span><br><span class="line">&gt;&gt;&gt; str = u"我爱北京天安门"</span><br><span class="line">&gt;&gt;&gt; str</span><br><span class="line">u'<span class="symbol">\u</span>6211<span class="symbol">\u</span>7231<span class="symbol">\u</span>5317<span class="symbol">\u</span>4eac<span class="symbol">\u</span>5929<span class="symbol">\u</span>5b89<span class="symbol">\u</span>95e8'</span><br></pre></td></tr></table></figure>

<p>Python 3.x</p>
<figure class="highlight ruby"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;</span>&gt; str = <span class="string">"我爱北京天安门"</span></span><br><span class="line"><span class="meta">&gt;&gt;</span>&gt; str</span><br><span class="line"><span class="string">'我爱北京天安门'</span></span><br></pre></td></tr></table></figure>

<hr>
<h4 id="除法运算"><a href="#除法运算" class="headerlink" title="除法运算"></a>除法运算</h4><p>Python中的除法较其它语言显得非常高端，有套很复杂的规则。Python中的除法有两个运算符，/和//</p>
<p>首先来说/除法:</p>
<p>在python 2.x中/除法就跟我们熟悉的大多数语言，比如Java啊C啊差不多，整数相除的结果是一个整数，把小数部分完全忽略掉，浮点数除法会保留小数点的部分得到一个浮点数的结果。</p>
<p>在python 3.x中/除法不再这么做了，对于整数之间的相除，结果也会是浮点数。</p>
<p>Python 2.x:</p>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; <span class="number">1</span> / <span class="number">2</span></span><br><span class="line"><span class="number">0</span></span><br><span class="line">&gt;&gt;&gt; <span class="number">1.0</span> / <span class="number">2.0</span></span><br><span class="line"><span class="number">0.5</span></span><br></pre></td></tr></table></figure>

<p>Python 3.x:</p>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; <span class="number">1</span>/<span class="number">2</span></span><br><span class="line"><span class="number">0.5</span></span><br></pre></td></tr></table></figure>

<p>而对于//除法，这种除法叫做floor除法，会对除法的结果自动进行一个floor操作，在python 2.x和python 3.x中是一致的。</p>
<p>python 2.x:</p>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; <span class="number">-1</span> <span class="comment">// 2</span></span><br><span class="line"><span class="number">-1</span></span><br></pre></td></tr></table></figure>

<p>python 3.x:</p>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; <span class="number">-1</span> <span class="comment">// 2</span></span><br><span class="line"><span class="number">-1</span></span><br></pre></td></tr></table></figure>

<p>注意的是并不是舍弃小数部分，而是执行 floor 操作，如果要截取整数部分，那么需要使用 math 模块的 trunc 函数</p>
<p>python 3.x:</p>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; <span class="keyword">import</span> math</span><br><span class="line">&gt;&gt;&gt; math.trunc(<span class="number">1</span> / <span class="number">2</span>)</span><br><span class="line"><span class="number">0</span></span><br><span class="line">&gt;&gt;&gt; math.trunc(<span class="number">-1</span> / <span class="number">2</span>)</span><br><span class="line"><span class="number">0</span></span><br></pre></td></tr></table></figure>

<h4 id="异常"><a href="#异常" class="headerlink" title="异常"></a>异常</h4><p>在 Python 3 中处理异常也轻微的改变了，在 Python 3 中我们现在使用 as 作为关键词。</p>
<p>捕获异常的语法由 <strong>except exc, var</strong> 改为 <strong>except exc as var</strong>。</p>
<p>使用语法except (exc1, exc2) as var可以同时捕获多种类别的异常。 Python 2.6已经支持这两种语法。</p>
<ul>
<li>\1. 在2.x时代，所有类型的对象都是可以被直接抛出的，在3.x时代，只有继承自BaseException的对象才可以被抛出。</li>
<li>\2. 2.x raise语句使用逗号将抛出对象类型和参数分开，3.x取消了这种奇葩的写法，直接调用构造函数抛出对象即可。</li>
</ul>
<p>在2.x时代，异常在代码中除了表示程序错误，还经常做一些普通控制结构应该做的事情，在3.x中可以看出，设计者让异常变的更加专一，只有在错误发生的情况才能去用异常捕获语句来处理。</p>
<hr>
<h4 id="xrange"><a href="#xrange" class="headerlink" title="xrange"></a>xrange</h4><p>在 Python 2 中 xrange() 创建迭代对象的用法是非常流行的。比如： for 循环或者是列表/集合/字典推导式。</p>
<p>这个表现十分像生成器（比如。”惰性求值”）。但是这个 xrange-iterable 是无穷的，意味着你可以无限遍历。</p>
<p>由于它的惰性求值，如果你不得仅仅不遍历它一次，xrange() 函数 比 range() 更快（比如 for 循环）。尽管如此，对比迭代一次，不建议你重复迭代多次，因为生成器每次都从头开始。</p>
<p>在 Python 3 中，range() 是像 xrange() 那样实现以至于一个专门的 xrange() 函数都不再存在（在 Python 3 中 xrange() 会抛出命名异常）。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> timeit</span><br><span class="line"></span><br><span class="line">n = <span class="number">10000</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">test_range</span><span class="params">(n)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">for</span> i <span class="keyword">in</span> range(n):</span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">test_xrange</span><span class="params">(n)</span>:</span></span><br><span class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> xrange(n):</span><br><span class="line">        <span class="keyword">pass</span></span><br></pre></td></tr></table></figure>

<p>Python 2</p>
<figure class="highlight sas"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">print <span class="string">'Python'</span>, python_versi<span class="meta">on(</span>)</span><br><span class="line"></span><br><span class="line">print <span class="string">'\ntiming range()'</span> </span><br><span class="line"><span class="name">%timeit</span> test<span class="meta">_range(</span>n)</span><br><span class="line"></span><br><span class="line">print <span class="string">'\n\ntiming xrange()'</span> </span><br><span class="line"><span class="name">%timeit</span> test_<span class="meta">xrange(</span>n)</span><br><span class="line"></span><br><span class="line">Python 2.7.6</span><br><span class="line"></span><br><span class="line">timing<span class="meta"> range(</span>)</span><br><span class="line">1000 loops, best of 3: 433 µs per loop</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">timing <span class="meta">xrange(</span>)</span><br><span class="line">1000 loops, best of 3: 350 µs per loop</span><br></pre></td></tr></table></figure>

<p>Python 3</p>
<figure class="highlight sas"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">p<span class="meta">rint(</span><span class="string">'Python'</span>, python_versi<span class="meta">on(</span>))</span><br><span class="line"></span><br><span class="line">p<span class="meta">rint(</span><span class="string">'\ntiming range()'</span>)</span><br><span class="line"><span class="name">%timeit</span> test<span class="meta">_range(</span>n)</span><br><span class="line"></span><br><span class="line">Python 3.4.1</span><br><span class="line"></span><br><span class="line">timing<span class="meta"> range(</span>)</span><br><span class="line">1000 loops, best of 3: 520 µs per loop</span><br><span class="line">p<span class="meta">rint(</span><span class="meta">xrange(</span>10))</span><br><span class="line">---------------------------------------------------------------------------</span><br><span class="line">NameError                                 Traceback (most recent <span class="meta">call</span> last)</span><br><span class="line">&lt;ipython-<span class="meta">input</span>-5-5d8f9b79ea70&gt; <span class="meta">in</span> &lt;module&gt;()</span><br><span class="line">----&gt; 1 p<span class="meta">rint(</span><span class="meta">xrange(</span>10))</span><br><span class="line"></span><br><span class="line">NameError: name <span class="string">'xrange'</span> is <span class="meta">not</span> defined</span><br></pre></td></tr></table></figure>

<h4 id="八进制字面量表示"><a href="#八进制字面量表示" class="headerlink" title="八进制字面量表示"></a>八进制字面量表示</h4><p>八进制数必须写成0o777，原来的形式0777不能用了；二进制必须写成0b111。</p>
<p>新增了一个bin()函数用于将一个整数转换成二进制字串。 Python 2.6已经支持这两种语法。</p>
<p>在Python 3.x中，表示八进制字面量的方式只有一种，就是0o1000。</p>
<p>python 2.x</p>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; <span class="number">0</span>o1000</span><br><span class="line"><span class="number">512</span></span><br><span class="line">&gt;&gt;&gt; <span class="number">01000</span></span><br><span class="line"><span class="number">512</span></span><br></pre></td></tr></table></figure>

<p>python 3.x</p>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; <span class="number">01000</span></span><br><span class="line">  File <span class="string">"&lt;stdin&gt;"</span>, line <span class="number">1</span></span><br><span class="line">    <span class="number">01000</span></span><br><span class="line">        ^</span><br><span class="line">SyntaxError: invalid token</span><br><span class="line">&gt;&gt;&gt; <span class="number">0</span>o1000</span><br><span class="line"><span class="number">512</span></span><br></pre></td></tr></table></figure>

<hr>
<h4 id="不等运算符"><a href="#不等运算符" class="headerlink" title="不等运算符"></a>不等运算符</h4><p>Python 2.x中不等于有两种写法 != 和 &lt;&gt;</p>
<p>Python 3.x中去掉了&lt;&gt;, 只有!=一种写法，还好，我从来没有使用&lt;&gt;的习惯</p>
<hr>
<h4 id="去掉了repr表达式"><a href="#去掉了repr表达式" class="headerlink" title="去掉了repr表达式``"></a>去掉了repr表达式``</h4><p>Python 2.x 中反引号``相当于repr函数的作用</p>
<p>Python 3.x 中去掉了``这种写法，只允许使用repr函数，这样做的目的是为了使代码看上去更清晰么？不过我感觉用repr的机会很少，一般只在debug的时候才用，多数时候还是用str函数来用字符串描述对象。</p>
<figure class="highlight reasonml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">def send<span class="constructor">Mail(<span class="params">from_</span>: <span class="params">str</span>, <span class="params">to</span>: <span class="params">str</span>, <span class="params">title</span>: <span class="params">str</span>, <span class="params">body</span>: <span class="params">str</span>)</span> -&gt; <span class="built_in">bool</span>:</span><br><span class="line">    pass</span><br></pre></td></tr></table></figure>

<hr>
<h4 id="多个模块被改名（根据PEP8）"><a href="#多个模块被改名（根据PEP8）" class="headerlink" title="多个模块被改名（根据PEP8）"></a>多个模块被改名（根据PEP8）</h4><table>
<thead>
<tr>
<th align="left">旧的名字</th>
<th align="left">新的名字</th>
</tr>
</thead>
<tbody><tr>
<td align="left">_winreg</td>
<td align="left">winreg</td>
</tr>
<tr>
<td align="left">ConfigParser</td>
<td align="left">configparser</td>
</tr>
<tr>
<td align="left">copy_reg</td>
<td align="left">copyreg</td>
</tr>
<tr>
<td align="left">Queue</td>
<td align="left">queue</td>
</tr>
<tr>
<td align="left">SocketServer</td>
<td align="left">socketserver</td>
</tr>
<tr>
<td align="left">repr</td>
<td align="left">reprlib</td>
</tr>
</tbody></table>
<p>StringIO模块现在被合并到新的io模组内。 new, md5, gopherlib等模块被删除。 Python 2.6已经支援新的io模组。</p>
<p>httplib, BaseHTTPServer, CGIHTTPServer, SimpleHTTPServer, Cookie, cookielib被合并到http包内。</p>
<p>取消了exec语句，只剩下exec()函数。 Python 2.6已经支援exec()函数。</p>
<h4 id="数据类型"><a href="#数据类型" class="headerlink" title="数据类型"></a>数据类型</h4><p>1）Py3.X去除了long类型，现在只有一种整型——int，但它的行为就像2.X版本的long</p>
<p>2）新增了bytes类型，对应于2.X版本的八位串，定义一个bytes字面量的方法如下：</p>
<figure class="highlight ruby"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;</span>&gt; b = b<span class="string">'china'</span> </span><br><span class="line"><span class="meta">&gt;&gt;</span>&gt; type(b) </span><br><span class="line">&lt;type <span class="string">'bytes'</span>&gt;</span><br></pre></td></tr></table></figure>

<p>str 对象和 bytes 对象可以使用 .encode() (<strong>str -&gt; bytes</strong>) 或 .decode() (<strong>bytes -&gt; str</strong>)方法相互转化。</p>
<figure class="highlight ruby"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;</span>&gt; s = b.decode() </span><br><span class="line"><span class="meta">&gt;&gt;</span>&gt; s </span><br><span class="line"><span class="string">'china'</span> </span><br><span class="line"><span class="meta">&gt;&gt;</span>&gt; b1 = s.encode() </span><br><span class="line"><span class="meta">&gt;&gt;</span>&gt; b1 </span><br><span class="line">b<span class="string">'china'</span></span><br></pre></td></tr></table></figure>

<p>3）dict的.keys()、.items 和.values()方法返回迭代器，而之前的iterkeys()等函数都被废弃。同时去掉的还有 dict.has_key()，用 in替代它吧 。</p>
<h4 id="打开文件"><a href="#打开文件" class="headerlink" title="打开文件"></a>打开文件</h4><p>原：</p>
<figure class="highlight gams"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="title">file</span>(<span class="params"> ..... </span>)</span></span><br><span class="line">或 </span><br><span class="line"><span class="function"><span class="title">open</span>(<span class="params">.....</span>)</span></span><br></pre></td></tr></table></figure>

<p>改为只能用</p>
<figure class="highlight gams"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="title">open</span>(<span class="params">.....</span>)</span></span><br></pre></td></tr></table></figure>

<p>从键盘录入一个字符串</p>
<p>原:</p>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="title">raw_input</span><span class="params">( <span class="string">"提示信息"</span> )</span></span></span><br></pre></td></tr></table></figure>

<p>改为:</p>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="title">input</span><span class="params">( <span class="string">"提示信息"</span> )</span></span></span><br></pre></td></tr></table></figure>

<p>在python2.x中raw_input()和input( )，两个函数都存在，其中区别为：</p>
<ul>
<li>raw_input()—将所有输入作为字符串看待，返回字符串类型</li>
<li>input()—–只能接收”数字”的输入，在对待纯数字输入时具有自己的特性，它返回所输入的数字的类型（int, float ）</li>
</ul>
<p>在python3.x中raw_input()和input( )进行了整合，去除了raw_input()，仅保留了input()函数，其接收任意任性输入，将所有输入默认为字符串处理，并返回字符串类型。</p>
<h4 id="map、filter-和-reduce"><a href="#map、filter-和-reduce" class="headerlink" title="map、filter 和 reduce"></a>map、filter 和 reduce</h4><p>这三个函数号称是函数式编程的代表。在 Python3.x 和 Python2.x 中也有了很大的差异。</p>
<p>首先我们先简单的在 Python2.x 的交互下输入 map 和 filter,看到它们两者的类型是 built-in function(内置函数):</p>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; map</span><br><span class="line">&lt;built-in function map&gt;</span><br><span class="line">&gt;&gt;&gt; filter</span><br><span class="line">&lt;built-in function filter&gt;</span><br><span class="line">&gt;&gt;&gt;</span><br></pre></td></tr></table></figure>

<p>它们输出的结果类型都是列表:</p>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; map(lambda x:x *<span class="number">2</span>, [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>])</span><br><span class="line">[<span class="number">2</span>, <span class="number">4</span>, <span class="number">6</span>]</span><br><span class="line">&gt;&gt;&gt; filter(lambda x:x %<span class="number">2</span> ==<span class="number">0</span>,range(<span class="number">10</span>))</span><br><span class="line">[<span class="number">0</span>, <span class="number">2</span>, <span class="number">4</span>, <span class="number">6</span>, <span class="number">8</span>]</span><br><span class="line">&gt;&gt;&gt;</span><br></pre></td></tr></table></figure>

<p>但是在Python 3.x中它们却不是这个样子了：</p>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&gt;&gt;&gt; map</span><br><span class="line">&lt;<span class="keyword">class</span> '<span class="symbol">map</span>'&gt;</span><br><span class="line">&gt;&gt;&gt; <span class="symbol">map</span>(<span class="symbol">print,</span>[<span class="symbol">1,<span class="symbol">2</span>,<span class="symbol">3</span></span>])</span><br><span class="line">&lt;<span class="symbol">map</span> <span class="symbol">object</span> <span class="symbol">at</span> <span class="symbol">0x10d8bd400</span>&gt;</span><br><span class="line">&gt;&gt;&gt; <span class="symbol">filter</span></span><br><span class="line">&lt;<span class="symbol">class</span> '<span class="symbol">filter</span>'&gt;</span><br><span class="line">&gt;&gt;&gt; <span class="symbol">filter</span>(<span class="symbol">lambda</span> <span class="symbol">x:<span class="symbol">x</span></span> % <span class="symbol">2</span> == <span class="symbol">0, <span class="symbol">range</span></span>(<span class="symbol">10</span>))</span><br><span class="line">&lt;<span class="symbol">filter</span> <span class="symbol">object</span> <span class="symbol">at</span> <span class="symbol">0x10d8bd3c8</span>&gt;</span><br><span class="line">&gt;&gt;&gt;</span><br></pre></td></tr></table></figure>

<p>首先它们从函数变成了类，其次，它们的返回结果也从当初的列表成了一个可迭代的对象, 我们尝试用 next 函数来进行手工迭代:</p>
<figure class="highlight ruby"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&gt;&gt;</span>&gt; f =filter(lambda <span class="symbol">x:</span>x %<span class="number">2</span> ==<span class="number">0</span>, range(<span class="number">10</span>))</span><br><span class="line"><span class="meta">&gt;&gt;</span>&gt; next(f)</span><br><span class="line"><span class="number">0</span></span><br><span class="line"><span class="meta">&gt;&gt;</span>&gt; next(f)</span><br><span class="line"><span class="number">2</span></span><br><span class="line"><span class="meta">&gt;&gt;</span>&gt; next(f)</span><br><span class="line"><span class="number">4</span></span><br><span class="line"><span class="meta">&gt;&gt;</span>&gt; next(f)</span><br><span class="line"><span class="number">6</span></span><br><span class="line"><span class="meta">&gt;&gt;</span>&gt;</span><br></pre></td></tr></table></figure>

<p>对于比较高端的 reduce 函数，它在 Python 3.x 中已经不属于 built-in 了，被挪到 functools 模块当中。</p>

    </div>

    
    
    

    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束 <i class="fa fa-paw"></i> 感谢您的阅读-------------</div>
    
</div>
      
    </div>
    
    <div>
      
        
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script src="https://cdn.bootcss.com/jquery/2.0.0/jquery.min.js"></script>
  <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
  <p><span>本文标题:</span><a href="/Python/Python_id_19.html">python基础知识(四)</a></p>
  <p><span>文章作者:</span><a href="/" title="访问 Yu ting 的个人博客">Yu ting</a></p>
  <p><span>发布时间:</span>2019年05月30日 - 00:05</p>
  <p><span>最后更新:</span>2020年06月02日 - 09:06</p>
  <p><span>原始链接:</span><a href="/Python/Python_id_19.html" title="python基础知识(四)">https://tian_yu_ting.gitee.io/Python/Python_id_19.html</a>
    <span class="copy-path"  title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="https://tian_yu_ting.gitee.io/Python/Python_id_19.html"  aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span><i class="fa fa-creative-commons"></i> <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
    $(".fa-clipboard").click(function(){
      clipboard.on('success', function(){
        swal({   
          title: "",   
          text: '复制成功',
          icon: "success", 
          showConfirmButton: true
          });
    });
    });  
</script>

      
    </div>
      
  <div class="popular-posts-header">相关文章推荐</div>
  <ul class="popular-posts">
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\Flask\Flask_id_01.html" rel="bookmark">flask中app上下文机制</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\Flask\Flask_id_02.html" rel="bookmark">flask开端</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\Flask\Flask_id_03.html" rel="bookmark">flask_migrate</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\Flask\Flask_id_04.html" rel="bookmark">flask_route</a></div>
    </li>
    <li class="popular-posts-item">
      <div class="popular-posts-title"><a href="\Flask\Flask_id_05.html" rel="bookmark">flask_script</a></div>
    </li>
  </ul>

        <div class="reward-container">
  <div>可以请我喝杯咖啡嘛</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/wechat.jpg" alt="Yu ting 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/images/alipay.jpg" alt="Yu ting 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Python/" rel="tag">分类： Python</a>
          </div>

        
  <div class="post-widgets">
    <div class="wp_rating">
      <div id="wpac-rating"></div>
    </div>
  </div>


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/Spider/Spider_id_14.html" rel="prev" title="进程线程协程">
      <i class="fa fa-chevron-left"></i> 进程线程协程
    </a></div>
      <div class="post-nav-item">
    <a href="/Python/Python_id_20.html" rel="next" title="python基础知识(五)">
      python基础知识(五) <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


              <!-- 此处可在文章模块中间添加东西 -->
          </div>
          <!-- 评论系统 -->
          <!--
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>
-->
        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#Python2-x与3-x版本区别"><span class="nav-text">Python2.x与3.x版本区别</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#print-函数"><span class="nav-text">print 函数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Unicode"><span class="nav-text">Unicode</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#除法运算"><span class="nav-text">除法运算</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#异常"><span class="nav-text">异常</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#xrange"><span class="nav-text">xrange</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#八进制字面量表示"><span class="nav-text">八进制字面量表示</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#不等运算符"><span class="nav-text">不等运算符</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#去掉了repr表达式"><span class="nav-text">去掉了repr表达式&#96;&#96;</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#多个模块被改名（根据PEP8）"><span class="nav-text">多个模块被改名（根据PEP8）</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#数据类型"><span class="nav-text">数据类型</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#打开文件"><span class="nav-text">打开文件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#map、filter-和-reduce"><span class="nav-text">map、filter 和 reduce</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Yu ting"
      src="/images/avatar.png">
  <p class="site-author-name" itemprop="name">Yu ting</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">171</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">16</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">66</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/yourname" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;yourname" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://mail.google.com/mail/u/0/#inbox" title="E-Mail → https:&#x2F;&#x2F;mail.google.com&#x2F;mail&#x2F;u&#x2F;0&#x2F;#inbox" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://weibo.com/u/6207787940" title="Weibo → https:&#x2F;&#x2F;weibo.com&#x2F;u&#x2F;6207787940" rel="noopener" target="_blank"><i class="fa fa-fw fa-weibo"></i>Weibo</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://news.google.com/?hl=zh-HK&gl=HK&ceid=HK%253Azh-Hant" title="Google → https:&#x2F;&#x2F;news.google.com&#x2F;?hl&#x3D;zh-HK&amp;gl&#x3D;HK&amp;ceid&#x3D;HK%3Azh-Hant" rel="noopener" target="_blank"><i class="fa fa-fw fa-google"></i>Google</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title">
      <i class="fa fa-fw fa-link"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://v3u.cn/" title="https:&#x2F;&#x2F;v3u.cn&#x2F;" rel="noopener" target="_blank">刘悦的技术博客</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="http://www.missbless.cn/" title="http:&#x2F;&#x2F;www.missbless.cn&#x2F;" rel="noopener" target="_blank">ISSAC　LOVELESS</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://www.f322.xyz/" title="https:&#x2F;&#x2F;www.f322.xyz&#x2F;" rel="noopener" target="_blank">逆の神様</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="http://www.wosowoso.com/" title="http:&#x2F;&#x2F;www.wosowoso.com&#x2F;" rel="noopener" target="_blank">素材网</a>
        </li>
    </ul>
  </div>

      </div>
      <div style="width:220px;text-align:center;padding-top:10px;margin-bottom:10px;border-bottom:1px dotted #000;"></div>
      <!-- 数字时钟 -->
      <!-- canvas粒子时钟 https://www.cnblogs.com/xiaohuochai/p/6368039.html
  https://www.html5tricks.com/html5-canvas-dance-time.html
 -->
<div id="">
  <canvas id="canvas" style="width:60%;">
</div>
<script>
(function(){
  var WINDOW_WIDTH = 820;
        var WINDOW_HEIGHT = 250;
        var RADIUS = 7; //球半径
        var NUMBER_GAP = 10; //数字之间的间隙
        var u=0.65; //碰撞能量损耗系数
        var context; //Canvas绘制上下文
        var balls = []; //存储彩色的小球
        const colors = ["#33B5E5","#0099CC","#AA66CC","#9933CC","#99CC00","#669900","#FFBB33","#FF8800","#FF4444","#CC0000"]; //彩色小球的颜色
        var currentNums = []; //屏幕显示的8个字符
        var digit =
                  [
                      [
                          [0,0,1,1,1,0,0],
                          [0,1,1,0,1,1,0],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [0,1,1,0,1,1,0],
                          [0,0,1,1,1,0,0]
                      ],//0
                      [
                          [0,0,0,1,1,0,0],
                          [0,1,1,1,1,0,0],
                          [0,0,0,1,1,0,0],
                          [0,0,0,1,1,0,0],
                          [0,0,0,1,1,0,0],
                          [0,0,0,1,1,0,0],
                          [0,0,0,1,1,0,0],
                          [0,0,0,1,1,0,0],
                          [0,0,0,1,1,0,0],
                          [1,1,1,1,1,1,1]
                      ],//1
                      [
                          [0,1,1,1,1,1,0],
                          [1,1,0,0,0,1,1],
                          [0,0,0,0,0,1,1],
                          [0,0,0,0,1,1,0],
                          [0,0,0,1,1,0,0],
                          [0,0,1,1,0,0,0],
                          [0,1,1,0,0,0,0],
                          [1,1,0,0,0,0,0],
                          [1,1,0,0,0,1,1],
                          [1,1,1,1,1,1,1]
                      ],//2
                      [
                          [1,1,1,1,1,1,1],
                          [0,0,0,0,0,1,1],
                          [0,0,0,0,1,1,0],
                          [0,0,0,1,1,0,0],
                          [0,0,1,1,1,0,0],
                          [0,0,0,0,1,1,0],
                          [0,0,0,0,0,1,1],
                          [0,0,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [0,1,1,1,1,1,0]
                      ],//3
                      [
                          [0,0,0,0,1,1,0],
                          [0,0,0,1,1,1,0],
                          [0,0,1,1,1,1,0],
                          [0,1,1,0,1,1,0],
                          [1,1,0,0,1,1,0],
                          [1,1,1,1,1,1,1],
                          [0,0,0,0,1,1,0],
                          [0,0,0,0,1,1,0],
                          [0,0,0,0,1,1,0],
                          [0,0,0,1,1,1,1]
                      ],//4
                      [
                          [1,1,1,1,1,1,1],
                          [1,1,0,0,0,0,0],
                          [1,1,0,0,0,0,0],
                          [1,1,1,1,1,1,0],
                          [0,0,0,0,0,1,1],
                          [0,0,0,0,0,1,1],
                          [0,0,0,0,0,1,1],
                          [0,0,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [0,1,1,1,1,1,0]
                      ],//5
                      [
                          [0,0,0,0,1,1,0],
                          [0,0,1,1,0,0,0],
                          [0,1,1,0,0,0,0],
                          [1,1,0,0,0,0,0],
                          [1,1,0,1,1,1,0],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [0,1,1,1,1,1,0]
                      ],//6
                      [
                          [1,1,1,1,1,1,1],
                          [1,1,0,0,0,1,1],
                          [0,0,0,0,1,1,0],
                          [0,0,0,0,1,1,0],
                          [0,0,0,1,1,0,0],
                          [0,0,0,1,1,0,0],
                          [0,0,1,1,0,0,0],
                          [0,0,1,1,0,0,0],
                          [0,0,1,1,0,0,0],
                          [0,0,1,1,0,0,0]
                      ],//7
                      [
                          [0,1,1,1,1,1,0],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [0,1,1,1,1,1,0],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [0,1,1,1,1,1,0]
                      ],//8
                      [
                          [0,1,1,1,1,1,0],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [1,1,0,0,0,1,1],
                          [0,1,1,1,0,1,1],
                          [0,0,0,0,0,1,1],
                          [0,0,0,0,0,1,1],
                          [0,0,0,0,1,1,0],
                          [0,0,0,1,1,0,0],
                          [0,1,1,0,0,0,0]
                      ],//9
                      [
                          [0,0,0,0],
                          [0,0,0,0],
                          [0,1,1,0],
                          [0,1,1,0],
                          [0,0,0,0],
                          [0,0,0,0],
                          [0,1,1,0],
                          [0,1,1,0],
                          [0,0,0,0],
                          [0,0,0,0]
                      ]//:
                  ];

        function drawDatetime(cxt){
            var nums = [];

            context.fillStyle="#005eac"
            var date = new Date();
            var offsetX = 70, offsetY = 30;
            var hours = date.getHours();
            var num1 = Math.floor(hours/10);
            var num2 = hours%10;
            nums.push({num: num1});
            nums.push({num: num2});
            nums.push({num: 10}); //冒号
            var minutes = date.getMinutes();
            var num1 = Math.floor(minutes/10);
            var num2 = minutes%10;
            nums.push({num: num1});
            nums.push({num: num2});
            nums.push({num: 10}); //冒号
            var seconds = date.getSeconds();
            var num1 = Math.floor(seconds/10);
            var num2 = seconds%10;
            nums.push({num: num1});
            nums.push({num: num2});

            for(var x = 0;x<nums.length;x++){
                nums[x].offsetX = offsetX;
                offsetX = drawSingleNumber(offsetX,offsetY, nums[x].num,cxt);
                //两个数字连一块，应该间隔一些距离
                if(x<nums.length-1){
                    if((nums[x].num!=10) &&(nums[x+1].num!=10)){
                        offsetX+=NUMBER_GAP;
                    }
                }
            }

            //说明这是初始化
            if(currentNums.length ==0){
                currentNums = nums;
            }else{
                //进行比较
                for(var index = 0;index<currentNums.length;index++){
                    if(currentNums[index].num!=nums[index].num){
                        //不一样时，添加彩色小球
                        addBalls(nums[index]);
                        currentNums[index].num=nums[index].num;
                    }
                }
            }
            renderBalls(cxt);
            updateBalls();

            return date;
        }

        function addBalls (item) {
            var num = item.num;
            var numMatrix = digit[num];
            for(var y = 0;y<numMatrix.length;y++){
                for(var x = 0;x<numMatrix[y].length;x++){
                    if(numMatrix[y][x]==1){
                        var ball={
                            offsetX:item.offsetX+RADIUS+RADIUS*2*x,
                            offsetY:30+RADIUS+RADIUS*2*y,
                            color:colors[Math.floor(Math.random()*colors.length)],
                            g:1.5+Math.random(),
                            vx:Math.pow(-1, Math.ceil(Math.random()*10))*4+Math.random(),
                            vy:-5
                        }
                        balls.push(ball);
                    }
                }
            }
        }

        function renderBalls(cxt){
            for(var index = 0;index<balls.length;index++){
                cxt.beginPath();
                cxt.fillStyle=balls[index].color;
                cxt.arc(balls[index].offsetX, balls[index].offsetY, RADIUS, 0, 2*Math.PI);
                cxt.fill();
            }
        }

        function updateBalls () {
            var i =0;
            for(var index = 0;index<balls.length;index++){
                var ball = balls[index];
                ball.offsetX += ball.vx;
                ball.offsetY += ball.vy;
                ball.vy+=ball.g;
                if(ball.offsetY > (WINDOW_HEIGHT-RADIUS)){
                    ball.offsetY= WINDOW_HEIGHT-RADIUS;
                    ball.vy=-ball.vy*u;
                }
                if(ball.offsetX>RADIUS&&ball.offsetX<(WINDOW_WIDTH-RADIUS)){

                    balls[i]=balls[index];
                    i++;
                }
            }
            //去除出边界的球
            for(;i<balls.length;i++){
                balls.pop();
            }
        }
        function drawSingleNumber(offsetX, offsetY, num, cxt){
            var numMatrix = digit[num];
            for(var y = 0;y<numMatrix.length;y++){
                for(var x = 0;x<numMatrix[y].length;x++){
                    if(numMatrix[y][x]==1){
                        cxt.beginPath();
                        cxt.arc(offsetX+RADIUS+RADIUS*2*x,offsetY+RADIUS+RADIUS*2*y,RADIUS,0,2*Math.PI);
                        cxt.fill();
                    }
                }
            }
            cxt.beginPath();
            offsetX += numMatrix[0].length*RADIUS*2;
            return offsetX;
        }

        var canvas = document.getElementById("canvas");
        canvas.width=WINDOW_WIDTH;
        canvas.height=WINDOW_HEIGHT;
        context = canvas.getContext("2d");

        //记录当前绘制的时刻
        var currentDate = new Date();

        setInterval(function(){
            //清空整个Canvas，重新绘制内容
            context.clearRect(0, 0, context.canvas.width, context.canvas.height);
            drawDatetime(context);
        }, 50)
})();
</script>

      <!-- 建站时间 -->
      
      
      <!-- 音乐 -->
<!--       <div>
        <audio src="/images/林俊杰 - 对的时间点.flac" autoplay="autoplay" controls="controls" loop="loop"></audio>
        
          <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=298 height=52 src="//music.163.com/outchain/player?type=2&id=569213220&auto=1&height=32"></iframe>
         
      </div> -->
    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heartbeat" style="color:red"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Yu ting</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">420k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">6:22</span>
</div>
  <div class="powered-by"><a href="https://weibo.com/u/3035313940" class="theme-link" rel="noopener" target="_blank">Only丶Nie</a>
  </div>
  <span class="post-meta-divider">|</span>
  <div class="powered-by"><a href="https://weibo.com/u/6207787940" class="theme-link" rel="noopener" target="_blank">余生有你才安好丶</a>
  </div>

        
<div class="busuanzi-count">
  <script async src="/js/busuanzi.js"></script>
  <!-- https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js -->
    <span class="post-meta-item" id="busuanzi_container_site_uv">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>总访问人数：
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>人
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>总访问量：
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>次
      </span>
    </span>
</div>







      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>


  <script defer src="/lib/three/three.min.js"></script>


  



  <script>
  if (CONFIG.page.isPost) {
    wpac_init = window.wpac_init || [];
    wpac_init.push({
      widget: 'Rating',
      id    : 24337,
      el    : 'wpac-rating',
      color : 'fc6423'
    });
    (function() {
      if ('WIDGETPACK_LOADED' in window) return;
      WIDGETPACK_LOADED = true;
      var mc = document.createElement('script');
      mc.type = 'text/javascript';
      mc.async = true;
      mc.src = '//embed.widgetpack.com/widget.js';
      var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(mc, s.nextSibling);
    })();
  }
  </script>

  
<script src="/js/local-search.js"></script>













  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : 'usjRVOXqGpbFIevxocLk2MXI-gzGzoHsz',
      appKey     : 'xd98ffpeQETblJ8uuGPacjjS',
      placeholder: "请在此处填写评论",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : true,
      lang       : 'zh-cn' || 'zh-cn',
      path       : location.pathname,
      recordIP   : true,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>


  <!-- 动画效果 -->
  

    <!-- 鼠标跟随 -->
  
  <!-- 鼠标指针 -->
  <style>
    body{cursor:url(/images/正常选择.cur),move}
    a{cursor:url(/images/链接选择.cur),wait} 
  </style>

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"jsonPath":"/live2dw/assets/koharu.model.json"},"display":{"position":"right","width":150,"height":300},"mobile":{"show":true},"log":false});</script></body>
</html>
